// Addin.h : Declaration of the CAddin

#pragma once
#include "resource.h"       // main symbols
#include "EncryptIt_i.h"
#include "Settings.h"

extern _ATL_FUNC_INFO OnSendInfo;
extern _ATL_FUNC_INFO OnOptionsAddPagesInfo;

class ATL_NO_VTABLE CAddin :
	public CComObjectRootEx<CComSingleThreadModel>,
	public CComCoClass<CAddin, &CLSID_Addin>,
	public ISupportErrorInfo,
	public IDispatchImpl<IAddin, &IID_IAddin, &LIBID_EncryptItLib, /*wMajor =*/ 1, /*wMinor =*/ 0>,
	public IDispatchImpl<_IDTExtensibility2, &__uuidof(_IDTExtensibility2), &LIBID_AddInDesignerObjects, /* wMajor = */ 1>,
	public IDispEventSimpleImpl<1,CAddin, &__uuidof(Outlook::ApplicationEvents)>//,
{
public:
	typedef IDispEventSimpleImpl</*nID =*/ 1, CAddin, &__uuidof(Outlook::ApplicationEvents)> AppEvents;

	CAddin():m_settings( Settings::Instance())
	{
	}

	DECLARE_REGISTRY_RESOURCEID(IDR_ADDIN)

	BEGIN_COM_MAP(CAddin)
		COM_INTERFACE_ENTRY(IAddin)
		COM_INTERFACE_ENTRY2(IDispatch, IAddin)
		COM_INTERFACE_ENTRY(ISupportErrorInfo)
		COM_INTERFACE_ENTRY(_IDTExtensibility2)
	END_COM_MAP()

	BEGIN_SINK_MAP(CAddin)
		SINK_ENTRY_INFO(1, __uuidof(Outlook::ApplicationEvents),/*dispid*/0x0000F002,OnSend,&OnSendInfo)
		SINK_ENTRY_INFO(1, __uuidof(Outlook::ApplicationEvents),/*dispid*/0xf005,OnOptionsAddPages,&OnOptionsAddPagesInfo)
	END_SINK_MAP()

	// ISupportsErrorInfo
	STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);

	DECLARE_PROTECT_FINAL_CONSTRUCT()

	HRESULT FinalConstruct()
	{
		return S_OK;
	}

	void FinalRelease()
	{
	}

	//event handlers	
	void __stdcall OnSend(IDispatch *Obj,VARIANT_BOOL *CancelDefault);
	void __stdcall OnOptionsAddPages(IDispatch* /*PropertyPages**/ Ctrl);

	// _IDTExtensibility2 Methods
public:
	STDMETHOD(OnConnection)(LPDISPATCH Application, ext_ConnectMode ConnectMode, LPDISPATCH AddInInst, SAFEARRAY * * custom)
	{
		//get pointer to Application root object
		CComQIPtr<Outlook::_Application> spApp(Application);		
		ATLASSERT(spApp);
		m_spApp = spApp;

		HRESULT hr = AppEvents::DispEventAdvise((IDispatch*)m_spApp,&__uuidof(Outlook::ApplicationEvents)); 
		if(FAILED(hr))
		{
			ATLTRACE("Failed advising to ApplicationEvents");
			return hr;
		}

		return S_OK;
	}
	STDMETHOD(OnDisconnection)(ext_DisconnectMode RemoveMode, SAFEARRAY * * custom)
	{
		AppEvents::DispEventUnadvise((IDispatch*)m_spApp);
		return S_OK;
	}
	STDMETHOD(OnAddInsUpdate)(SAFEARRAY * * custom)
	{
		return S_OK;
	}
	STDMETHOD(OnStartupComplete)(SAFEARRAY * * custom)
	{
		return S_OK;
	}
	STDMETHOD(OnBeginShutdown)(SAFEARRAY * * custom)
	{
		return S_OK;
	}

private:
	Settings &m_settings;
	CComPtr<Outlook::_Application> m_spApp;
public:
	static std::wstring DLLPATH;
};

OBJECT_ENTRY_AUTO(__uuidof(Addin), CAddin)
